import requests
from lxml import etree
import  os
if __name__ == "__main__":
    # 爬取页面源码数据
    headers = {
        'user-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
    }

    url = 'https://pic.netbian.com/4kmeinv/'
    response = requests.get(url=url,headers=headers)
    response.encoding = 'gbk'
    page_text = response.text
    #解析src的属性值
    tree = etree.HTML(page_text)
    li_list = tree.xpath('//div[@class="slist"]/ul/li')
    if not os.path.exists('./picLibs'):
        os.mkdir('./picLibs')

    for li in li_list:
        img_src = 'https://pic.netbian.com'+li.xpath('a/img/@src')[0]
        img_name = li.xpath('a/img/@alt')[0]+'.jpg'

        #请求图片进行持久化存储
        img_data = requests.get(url=img_src,headers=headers).content
        img_path = 'picLibs/'+img_name
        with open(img_path,'wb') as fp:
            fp.write(img_data)
            print(img_name,'下载成功！！')
